package io.plus.engine.client;

import io.plus.engine.utils.lock_capable_task.AbstractTask;
import lombok.extern.slf4j.Slf4j;
import tool.plus.Clock;

import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

@Slf4j
public class ReConnectTask extends AbstractTask {
    ClientAsynchronousSocketChannelContext clientAsynchronousSocketChannelContext = null;
    Client client = null;


    public ReConnectTask(ClientAsynchronousSocketChannelContext clientAsynchronousSocketChannelContext, Client client, Executor executor) {
        super(executor);
        this.clientAsynchronousSocketChannelContext = clientAsynchronousSocketChannelContext;
        this.client = client;
    }

    @Override
    public boolean isNeededExecute() {
        return false;
    }

    @Override
    public void runTask() {
        clientAsynchronousSocketChannelContext.getReConnectCount().incrementAndGet();
        ReentrantReadWriteLock closeLock = clientAsynchronousSocketChannelContext.closeLock;
        WriteLock writeLock = closeLock.writeLock();
        writeLock.lock();
        try {
            //已经连上了，不需要再重连了
            if (!clientAsynchronousSocketChannelContext.isClosed) {
                return;
            }
            long start = Clock.currentTimeMillis;
            client.reconnect(clientAsynchronousSocketChannelContext, 2);
            long end = Clock.currentTimeMillis;
            long interval = end - start;
            log.error("{}, 第{}次重连,重连耗时:{} ms", clientAsynchronousSocketChannelContext, clientAsynchronousSocketChannelContext.getReConnectCount(), interval);
        } catch (java.lang.Throwable e) {
            log.error(e.toString(), e);
        } finally {
            writeLock.unlock();
        }

    }
}
